<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
      <el-form-item label="区域名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入区域名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 240px">
          <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="queryParams.sort" placeholder="请输入排序" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item> -->
     
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作栏 -->
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button icon="Upload" @click="handleImport">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="Download" @click="handleExport">导出</el-button>
      </el-col> -->
         <el-col :span="1.5">
            <el-button
               type="primary"
               plain
               icon="Plus"
               @click="handleAdd"
                v-hasPermi="['pms:area:add']"
              
            >新增</el-button>
         </el-col>
          <!-- <el-col :span="1.5">
            <el-button
               type="success"
               plain
               icon="Edit"
               :disabled="single"
               @click="handleEdit()"
               v-hasPermi="['pms:area:edit']"
            >修改</el-button>
         </el-col> -->
           <!-- <el-col :span="1.5">
            <el-button
               type="danger"
               plain
               icon="Delete"
               :disabled="multiple"
               @click="handleDelete"
               v-hasPermi="['pms:area:remove']"
            >删除</el-button>
         </el-col> -->
    </el-row>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="areaList"
      row-key="id"
      :tree-props="{ children: 'childs' }"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="区域名称" prop="name" :show-overflow-tooltip="true" />
      
      <!-- <el-table-column label="排序" prop="sort" width="80" /> -->
      <el-table-column label="创建时间" prop="createDate" width="180" />
      <el-table-column label="区域编码" prop="code" width="180" />
      <el-table-column label="更新时间" prop="updateTime" width="180" />
      <el-table-column label="操作" align="center" width="300" >
        <template #default="scope">
          <el-button v-hasPermi="['pms:area:add']" link type="primary" v-if="scope.row.status == 1"  icon="Plus" @click="handleAddChild(scope.row)" >新增</el-button>
          <el-button v-hasPermi="['pms:area:edit']" link type="primary"  v-if="scope.row.level === 1"  icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button v-hasPermi="['pms:area:remove']" link type="primary"  v-if="scope.row.level === 1" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button  link type="success" icon="Plus" v-if="scope.row.level === 1" @click="handleAddBuilding(scope.row)">新增楼宇</el-button>
          <el-button  link type="warning" icon="Plus" v-if="scope.row.level === 2" @click="handleAddFloor(scope.row)">新增单元</el-button>
           <el-button v-hasPermi="['pms:area:remove']" link type="primary"  v-if="scope.row.level === 2" icon="Delete" @click="handleDeleteBuildOrUnit(scope.row)">删除</el-button>
          <el-button link type="primary" icon="Edit" v-if="scope.row.level === 2" @click="handleEditBuildingOrFloor(scope.row)">编辑楼宇</el-button>
          <el-button link type="primary" icon="Edit" v-if="scope.row.level === 3" @click="handleEditBuildingOrFloor(scope.row)">编辑单元</el-button>
          <el-button v-hasPermi="['pms:area:remove']" link type="primary"  v-if="scope.row.level === 3" icon="Delete" @click="handleDeleteBuildOrUnit(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 空数据提示 -->
   

    <!-- 新增/编辑区域弹窗 -->
    <el-dialog :close-on-click-modal="false"  
    @close="handleClose" :title="dialogTitle"
     v-model="dialogVisible" width="600px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <!-- <el-form-item label="上级区域" prop="parentId">
          <el-tree-select
          default-expand-all
            v-model="form.parentId"
            :data="areaOptions"
            :props="{ value: 'areaId', label: 'name', children: 'childs' }"
            value-key="areaId"
            placeholder="请选择上级区域"
            check-strictly
            style="width: 100%"
          />
        </el-form-item> -->
        <!-- <el-form-item  v-if="!form.parentId" label="所属小区" prop="communityId">
          <el-select v-model="form.communityId" placeholder="请选择小区" style="width: 100%">
            <el-option
              v-for="item in communityOptions"
              :key="item.communityId"
              :label="item.name"
              :value="item.communityId"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="区域名称" prop="name" required>
          <el-input v-model="form.name" placeholder="请输入区域名称" />
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">停用</el-radio>
          </el-radio-group>
        </el-form-item> -->
        
        <!-- <el-form-item v-if="!form.areaId" label="区域编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入区域编码" />
        </el-form-item> -->
        <!-- <div v-if="!form.areaId" style="color: red;font-size: 14px;margin-bottom: 10px;margin-left: 100px;">区域编号不可更改</div> -->
        <!-- <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" style="width: 100%" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">关闭</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增楼宇弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="buildDialogTitle"
      v-model="buildingDialogVisible"
      width="400px"
      append-to-body
    >
      <el-form ref="buildingFormRef" :model="buildingForm" :rules="buildDialogIsFloor ? floorRules : buildRules" label-width="80px">
        <el-form-item v-if="!buildDialogIsFloor" label="楼宇名称" prop="name">
          <el-input v-model="buildingForm.name" placeholder="请输入楼宇名称" />
        </el-form-item>
        <el-form-item v-if="buildDialogIsFloor" label="单元名" prop="name">
          <el-input v-model="buildingForm.name" placeholder="请输入单元名" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="buildingDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleSaveBuildingOrFloor">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增单元弹窗 -->
    <el-dialog
    :close-on-click-modal="false"
      :title="'新增单元'"
      v-model="floorDialogVisible"
      width="400px"
      append-to-body
    >
      <el-form ref="floorFormRef" :model="floorForm" :rules="floorRules" label-width="80px">
        <el-form-item label="单元名" prop="name">
          <el-input v-model="floorForm.name" placeholder="请输入单元名" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="floorDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleSaveFloor">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs,onMounted } from 'vue'
import { listArea, addArea, 
updateArea, delArea,addBuild,addFloor,editBuild,editFloor,deltBuild,deltUnit } from '@/api/house/area'
import { listCommunity } from '@/api/house/community'
// import { addBuilding } from '@/api/house/building'
import { number } from 'echarts'

const { proxy } = getCurrentInstance()
const statusOptions = [
  { value: '1', label: '正常' },
  { value: '2', label: '停用' }
]

const loading = ref(false)
const areaList = ref([])
const total = ref(0)
const multiple = ref(true)
const ids = ref([])

const data = reactive({
  queryParams: {
    //  communityId:0,
    // parentId: 0,
    pageNum: 1,
    pageSize: 10,
    name: '',
    // status: '',
    // sort: ''
  }
})
const { queryParams } = toRefs(data)

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增')
const formRef = ref(null)
const communityOptions = ref([])
const areaOptions = ref([])
const single = ref([])
const form = reactive({
  parentId: '',
  name: '',
  status: '1',
  sort: '',
  communityId: '',
  level: 1 // 默认最外层
})
const rules = {
  name: [{ required: true, message: '请输入区域名称', trigger: 'blur' }],
  sort: [
    { required: true, message: '请输入排序', trigger: 'change' },
    { type: 'number', message: '排序必须为数字', trigger: 'change' },
    { validator: (rule, value, callback) => {
        if (value === null || value === undefined || value === '') {
          callback(new Error('请输入排序'))
        } else {
          callback()
        }
      }, trigger: 'change'
    }
  ],
  communityId: [{ required: true, message: '请选择小区', trigger: 'change' }]
}

// 楼宇弹窗相关
const buildingDialogVisible = ref(false)
const floorDialogVisible = ref(false)
const buildingFormRef = ref(null)
const buildingForm = reactive({
  id: null,
  name: '',
  areaId: null,
  buildId: null,
  communityId: null
})
const buildDialogIsFloor = ref(false) // true: 单元，false: 楼宇
const buildDialogTitle = ref('')
const buildRules = {
  name: [{ required: true, message: '请输入楼宇名称', trigger: 'blur' }]
}
const floorRules = {
  name: [{ required: true, message: '请输入单元名', trigger: 'blur' }]
}

function handleClose() {
  dialogVisible.value = false
  formRef.value.resetFields()
}

function normalizeAreaTree(data, parentLevel = 0) {
  // 递归处理每一层
  return data.map(area => {
    const level = parentLevel + 1;
    // 一级区域
    const areaNode = {
      ...area,
      id: area.areaId || area.id,
      level,
      childs: []
    };
    // 二级楼宇
    if (Array.isArray(area.pmsBuilds)) {
      areaNode.childs = area.pmsBuilds.map(build => {
        const buildNode = {
          ...build,
          id: build.id || build.buildId,
          level: level + 1,
          childs: []
        };
        // 三级单元
        if (Array.isArray(build.units)) {
          buildNode.childs = build.units.map(unit => ({
            ...unit,
            id: unit.id || unit.unitId,
            level: level + 2,
            childs: []
          }));
        }
        return buildNode;
      });
    }
    return areaNode;
  });
}

function getList() {
  loading.value = true
  listArea({
    pageNum: 1,
    pageSize: 1000,
    status:1
  })
  .then(res => {
    areaOptions.value =  [
      {
        areaId:0,
        name:"最上级",
        childs: res?.rows || []
      }
    ]
  })
  listArea(queryParams.value).then(res => {
    let flatList = res?.rows || []
    flatList = normalizeAreaTree(flatList)
    console.log("flatList",flatList)
    areaList.value = flatList
    total.value = flatList.length
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function resetQuery() {
  queryParams.value.name = ''
  queryParams.value.status = ''
  queryParams.value.sort = ''
  handleQuery()
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.areaId)
  multiple.value = !selection.length
  single.value = selection.length != 1

}

function handleAdd() {
  dialogTitle.value = '新增'
  form.parentId = ''
  form.name = ''
  form.status = 1
  form.sort = ''
  form.communityId = ''
  form.areaId = ''
  form.level = 1 // 新增最外层
  dialogVisible.value = true
  formRef.value.resetFields()
}
function handleEdit(row) {
  if(!row){
    let id=ids.value[0]
    row=areaList.value.find(item => item.areaId == id)
  }
 
  if(row.status == 2){
    proxy.$modal.msgError("该区域已停用，无法编辑")
    return
  }
  console.log("row",row)
  dialogTitle.value = '编辑'
  form.areaId = row.areaId
  form.parentId = row.parentId 
  form.name = row.name 
  form.status = Number(row.status) 
  form.sort =  Number(row.sort) 
  form.communityId =Number(row.communityId) 
  form.code = row.code 
  
  console.log("form",form)
  dialogVisible.value = true
}
function handleDelete(row) {
  const delIds = row ? [row.areaId] : ids.value
  if (!delIds.length) return

  // 检查是否有子集数据
  let hasChildren = false
  let childrenInfo = []
  
  if (row) {
    // 单个删除时检查该区域是否有楼宇
    if (row.childs && row.childs.length > 0) {
      hasChildren = true
      childrenInfo.push(`该区域下有 ${row.childs.length} 个楼宇`)
      
      // 进一步检查楼宇下是否有单元
      let totalUnits = 0
      row.childs.forEach(building => {
        if (building.childs && building.childs.length > 0) {
          totalUnits += building.childs.length
        }
      })
      if (totalUnits > 0) {
        childrenInfo.push(`共包含 ${totalUnits} 个单元`)
      }
    }
  } else {
    // 批量删除时检查所有选中的区域
    delIds.forEach(id => {
      const area = areaList.value.find(item => item.areaId == id)
      if (area && area.childs && area.childs.length > 0) {
        hasChildren = true
        childrenInfo.push(`区域"${area.name}"下有 ${area.childs.length} 个楼宇`)
      }
    })
  }

  let confirmMessage = '是否确认删除区域编号为"' + delIds + '"的数据项?'
  
  if (hasChildren) {
    confirmMessage = `警告：${childrenInfo.join('，')}。\n\n确定要继续删除吗？`
  }

  proxy.$modal.confirm(confirmMessage).then(function () {
    return delArea(delIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}
function handleImport() {
  // 预留导入逻辑
}
function handleExport() {
  // 预留导出逻辑
}
function handleSave() {
  formRef.value.validate(valid => {
    if (valid) {
      let level = 1
      if (form.parentId && form.parentId !== '0' && form.parentId !== 0) {
        level = getParentLevel(form.parentId)
      }
      // 自动生成 code
      const parentNames = getParentNames(form.parentId)
      const code = parentNames.length > 0 ? parentNames.concat([form.name]).join('#') : form.name
      const payload = {
        areaId: form.areaId,
        parentId: form.parentId,
        name: form.name,
        status: Number(form.status),
        sort: Number(form.sort),
        communityId: Number(form.communityId),
        code: code,
        level: level
      }
      if(form.areaId){
        // 编辑时不允许改 code
        delete payload.code
      }
      const req = dialogTitle.value === '编辑' ? updateArea(payload) : addArea(payload)
      req.then(() => {
        window.$message?.success?.('保存成功') || this?.$message?.success('保存成功')
        dialogVisible.value = false
        handleClose()
        getList()
      })
    }
  })
}

function handleAddChild(parent) {
  dialogTitle.value = '新增'
  form.parentId = parent.areaId
  form.name = ''
  form.status = 1
  form.sort = ''
  form.communityId = parent.communityId
  form.code = undefined
  form.areaId = undefined
  form.level = (parent.level ? Number(parent.level) + 1 : getParentLevel(parent.areaId))
  dialogVisible.value = true
}

// 递归查找父级 level
function getParentLevel(parentId) {
  if (!parentId || parentId === '0' || parentId === 0) {
    return 1
  }
  const parent = areaList.value.find(item => item.areaId == parentId)
  if (parent && parent.level) {
    return Number(parent.level) + 1
  } else if (parent) {
    return getParentLevel(parent.parentId) + 1
  } else {
    return 2
  }
}

// 递归查找所有上级 name
function getParentNames(parentId) {
  if (!parentId || parentId === '0' || parentId === 0) {
    return []
  }
  const parent = areaList.value.find(item => item.areaId == parentId)
  if (parent) {
    return [...getParentNames(parent.parentId), parent.name]
  } else {
    return []
  }
}

// 新增楼宇
function handleAddBuilding(area) {
  buildDialogTitle.value = '新增楼宇'
  buildDialogIsFloor.value = false
  buildingForm.id = null
  buildingForm.name = ''
  buildingForm.areaId = area.areaId
  buildingForm.buildId = null
  buildingForm.communityId = area.communityId
  buildingDialogVisible.value = true
}

// 新增单元
function handleAddFloor(build) {
  buildDialogTitle.value = '新增单元'
  buildDialogIsFloor.value = true
  buildingForm.id = null
  buildingForm.name = ''
  buildingForm.areaId = null
  buildingForm.buildId = build.id
  buildingForm.communityId = build.communityId
  buildingDialogVisible.value = true
}

// 编辑（楼宇或单元）
function handleEditBuildingOrFloor(row) {
  if (row.level === 2) {
    buildDialogTitle.value = '编辑楼宇'
    buildDialogIsFloor.value = false
    buildingForm.id = row.id
    buildingForm.name = row.name
    buildingForm.areaId = row.areaId
    buildingForm.buildId = null
    buildingForm.communityId = row.communityId
  } else if (row.level === 3) {
    buildDialogTitle.value = '编辑单元'
    buildDialogIsFloor.value = true
    buildingForm.id = row.id
    buildingForm.name = row.name
    buildingForm.areaId = null
    buildingForm.buildId = row.buildId
    buildingForm.communityId = row.communityId
  }
  buildingDialogVisible.value = true
}

// 保存（楼宇或单元）
function handleSaveBuildingOrFloor() {
  buildingFormRef.value.validate(valid => {
    if (valid) {
      if (!buildDialogIsFloor.value) {
        // 楼宇
        const payload = {
          id: buildingForm.id,
          name: buildingForm.name,
          areaId: buildingForm.areaId,
          communityId: buildingForm.communityId
        }
        const req = buildingForm.id ? editBuild(payload) : addBuild(payload)
        req.then(() => {
          proxy.$message?.success('保存成功')
          buildingDialogVisible.value = false
          getList()
        })
      } else {
        // 单元
        const payload = {
          id: buildingForm.id,
          name: buildingForm.name,
          buildId: buildingForm.buildId,
          communityId: buildingForm.communityId
        }
        const req = buildingForm.id ? editFloor(payload) : addFloor(payload)
        req.then(() => {
          proxy.$message?.success('保存成功')
          buildingDialogVisible.value = false
          getList()
        })
      }
    }
  })
}

// 删除楼宇或单元
function handleDeleteBuildOrUnit(row) {
  if (row.level === 2) {
    // 删除楼宇时检查是否有单元
    let confirmMessage = '是否确认删除楼宇"' + row.name + '"？'
    
    if (row.childs && row.childs.length > 0) {
      confirmMessage = `警告：楼宇"${row.name}"下有 ${row.childs.length} 个单元。\n\n确定要继续删除吗？`
    }
    
    proxy.$modal.confirm(confirmMessage).then(function () {
      return deltBuild(row.id)
    }).then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    }).catch(() => {})
  } else if (row.level === 3) {
    // 单元删除无需额外检查，因为单元是最底层
    proxy.$modal.confirm('是否确认删除单元"' + row.name + '"？').then(function () {
      return deltUnit(row.id)
    }).then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    }).catch(() => {})
  }
}

onMounted(() => {
  listCommunity().then(res => {
    communityOptions.value = res.rows || []
  })
})

getList()
</script>